﻿import haxe.xml.Fast;

class PetsServerApi extends ServerApi
{  
	private static inline var serverURL : String = "http://localhost/index.php";
	private static inline var authKey : String = "";
	private static inline var appName : String = "";
	
	
	public function new(viewerId : Int) 
	{
		super(serverURL, authKey, viewerId, appName);
	}
	
	public function addPet(owner, species, name , onComplete1: Pet -> Void)
	{    
		var params = {
			method: "add", owner: owner, species: species, name: name
		};
		
		var onComplete = function(xml : Xml) {
			try { 
		    var response = xml.firstElement();
			
			if (response.nodeName == "error") {
				trace("error");
			} else if (response.nodeName == "response") {
				trace("Add");
			var fast:Fast = new Fast(response.firstElement());	
		    var  id = fast.node.id.innerHTML;
			var owner = fast.node.owner.innerHTML;
			var species = fast.node.species.innerHTML;
			var name = fast.node.name.innerHTML;
			var apet = new Pet(id,owner, species ,name );
				onComplete1(apet);
              
			}
		
			} catch (e: Dynamic) {
				trace(e);
			}
		};
		
		this.request("", params, onComplete, onError);
		
	}
	
	
public function PetsList(onComplete2)
{
	var params = {
		method: "list"
	};
	
	var onCompleteList = function(xml : Xml) {
		try { 
		    var response = xml.firstElement();
           
			if (response.nodeName == "error") {
				trace("error");
			} else if (response.nodeName == "response") {
				trace("List");
			var fast:Fast = new Fast(response);	
			for (p in fast.elements) 
			   {
			    var  id = p.node.id.innerHTML;	
				var owner = p.node.owner.innerHTML;
			    var species = p.node.species.innerHTML;
			    var name = p.node.name.innerHTML;
			    var apet = new Pet(id,owner, species ,name );
				onComplete2(apet);
			   }
			}
		
			} catch (e: Dynamic) {
				trace(e);
			}
		
	};
	
	this.request("", params, onCompleteList, onError);
}

public  function PetDelete(id:String)
{
	var params = {
		method: "delete", id:id
	};
	 trace("delete: " +id ); 
	var onCompleteDelete = function(xml : Xml) {
		trace(xml);
		
	};
	PetsList(function(pet) { trace(pet.id + ". " + pet.owner+ " " + pet.species+ " " + pet.name); });
	this.request("", params, onCompleteDelete, onError);
}


	private function onError(s : String) : Void
	{
		trace(s);
	}
	
}